######################################################################## # PLS 206 — Week 9: Transformations and MANOVA # Grey Monroe, Fall 2026 # # Every block is tagged: # [CORE] the analysis: code you would run on your own data # [HANDY] useful, not essential: wrangling, plotting, small helpers # [DEMO] for the lecture only: simulated data, sums by hand, and the # code behind slide figures ######################################################################## # [CORE] # install.packages(c("ggplot2", "patchwork", "MASS", "vegan")) library(ggplot2) library(patchwork) library(MASS) # boxcox() and lda() library(vegan) # adonis2() and betadisper(), plus the dune data ######################################################################## # PART A. Transformations ######################################################################## # ---- 1) The data: 60 soil cores -------------------------------------- # Each core has its soil organic carbon (SOC, %) and its microbial # biomass carbon (µg C per g of soil). The question: how does microbial # biomass change with soil carbon? (Hypothetical, simulated data.) # [CORE] soil <- read.csv("https://greymonroe.github.io/PLS_206/data/soil_microbes.csv") head(soil) p_soil <- ggplot(soil, aes(soc, microbial_biomass)) + geom_point(size = 2) + labs(x = "Soil organic carbon (%)", y = "Microbial biomass (µg C / g)") + theme_classic(base_size = 14) p_soil # Two things stand out. The cloud curves upward, and it fans out: cores # with more carbon vary far more than cores with little. # ---- 2) A straight line on the raw scale ----------------------------- # [CORE] m_raw <- lm(microbial_biomass ~ soc, data = soil) grid <- data.frame(soc = seq(min(soil$soc), max(soil$soc), length.out = 100)) fit_raw <- cbind(grid, predict(m_raw, grid, interval = "confidence")) p_soil + geom_ribbon(data = fit_raw, aes(soc, ymin = lwr, ymax = upr), inherit.aes = FALSE, fill = "red", alpha = 0.2) + geom_line(data = fit_raw, aes(soc, fit), colour = "red", linewidth = 1) # The line misses the curve: it runs above the data in the middle and # below it at both ends. The residuals show the second problem, the # fan: # [CORE] plot(m_raw, which = 1) # Residuals that spread out as the fitted values grow break the # equal-variance assumption, so the standard errors and p-values of # this model can't be trusted. # ---- 3) Log the response --------------------------------------------- # A log turns multiplying into adding. If biomass grows by the same # percentage for each extra unit of carbon, then log(biomass) grows by # the same amount, which is a straight line. # [DEMO: the response before and after the log] h_raw <- ggplot(soil, aes(microbial_biomass)) + geom_histogram(bins = 15, fill = "grey70", colour = "black") + labs(x = "Microbial biomass (µg C / g)", y = "Cores", title = "Raw: long right tail") + theme_classic(base_size = 14) h_log <- ggplot(soil, aes(log(microbial_biomass))) + geom_histogram(bins = 15, fill = "lightblue", colour = "black") + labs(x = "log(microbial biomass)", y = "Cores", title = "Log: symmetric") + theme_classic(base_size = 14) h_raw + h_log # ---- 4) Fit the line on the log scale -------------------------------- # Put the log inside the formula. R fits the model to log(biomass); the # data frame stays as it is. # [CORE] m_log <- lm(log(microbial_biomass) ~ soc, data = soil) summary(m_log) # [CORE] fit_log <- cbind(grid, predict(m_log, grid, interval = "confidence")) ggplot(soil, aes(soc, log(microbial_biomass))) + geom_point(size = 2) + geom_ribbon(data = fit_log, aes(soc, ymin = lwr, ymax = upr), inherit.aes = FALSE, fill = "blue", alpha = 0.2) + geom_line(data = fit_log, aes(soc, fit), colour = "blue", linewidth = 1) + labs(x = "Soil organic carbon (%)", y = "log(microbial biomass)") + theme_classic(base_size = 14) # On the log scale the points follow the line and the spread is even. # The residual plot agrees: no fan. # [CORE] plot(m_log, which = 1) # ---- 5) Back-transform to the original units ------------------------- # Nobody thinks in log(µg C / g). Undo the log with exp(): on the # fitted line, on its confidence band, and on the slope. # [CORE] fit_back <- fit_log fit_back[, c("fit", "lwr", "upr")] <- exp(fit_log[, c("fit", "lwr", "upr")]) p_soil + geom_ribbon(data = fit_back, aes(soc, ymin = lwr, ymax = upr), inherit.aes = FALSE, fill = "blue", alpha = 0.2) + geom_line(data = fit_back, aes(soc, fit), colour = "blue", linewidth = 1) # The model is a straight line on the log scale and a curve in the # original units, and it follows the data. Back-transformed, the slope # becomes a multiplier: # [CORE] exp(coef(m_log)) exp(confint(m_log)) # Each extra 1% of soil carbon multiplies microbial biomass by about # 1.67 (95% CI 1.48 to 1.88), a 67% increase. Two things to remember # when you report a back-transformed model: # - The back-transformed line is the geometric mean (roughly the # median) of biomass at each SOC, not the arithmetic mean. With a long # right tail, the arithmetic mean sits above it. - Back-transform the # ends of the confidence interval, never the standard error. That is # why the band is wider above the line than below it. # ---- 6) Let Box-Cox pick the power ----------------------------------- # Not sure which transformation? boxcox() tries a family of powers, # y^λ, and shows how well each one fits. λ = 1 is no transformation, λ # = 0.5 is the square root, λ = 0 is the log, λ = −1 is the reciprocal. # [CORE] bc <- boxcox(m_raw, lambda = seq(-1, 1, 0.05)) bc$x[which.max(bc$y)] # the best lambda # The best λ is 0. The 95% interval (the dashed lines, about −0.25 to # 0.27) includes 0 and excludes the square root (0.5) and no # transformation (1): the log is the right call. In practice, treat # Box-Cox as a guide and round to a transformation you can explain # (log, square root, reciprocal). Box-Cox needs a positive response. # ---- 7) Which transformation for which data -------------------------- # | Your response | Transformation | The alternative from Week 3 | # |---|---|---| | Positive, right-skewed, spread grows with the mean # (biomass, concentrations, gene expression) | log(y) | Gamma or # lognormal GLM, family = Gamma(link = "log") | | Counts (insects, # lesions, seeds) | sqrt(y) | Poisson or negative binomial GLM | | # Proportions between 0 and 1 (germination, cover) | logit, qlogis(p) | # Binomial GLM | | Contains zeros and needs a log | log(y + 1), with # care: the answer depends on the "+1" | A GLM handles zeros directly | # | Hopeless distribution, only the order matters | rank(y) | # Non-parametric tests (Kruskal-Wallis, Week 1) | # A transformation and a GLM answer slightly different questions. # lm(log(y) ~ x) models the mean of log(y), the geometric mean. glm(y ~ # x, family = Gamma(link = "log")) models the log of the mean of y, the # arithmetic mean. For skewed positive data both are standard; use the # GLM when you need predictions of the average in original units, or # when the data have zeros. # [HANDY: the logit and its inverse] p <- c(0.05, 0.5, 0.95) qlogis(p) # logit: log(p / (1 - p)) plogis(qlogis(p)) # inverse logit brings it back # ---- 8) Transforming predictors: `scale()` --------------------------- # Predictors can be transformed too. scale() centres a variable # (subtracts its mean) and divides by its standard deviation, so every # predictor is in standard-deviation units. You used it for PCA and # clustering. In a regression it changes the units of a slope, not the # fit. # [HANDY] soil$soc_z <- as.numeric(scale(soil$soc)) coef(lm(log(microbial_biomass) ~ soc_z, data = soil)) # change in log(biomass) per 1 SD of SOC # Same model, same p-value, same predictions; only the slope's units # changed. Scaling is useful when you compare slopes of predictors # measured in different units, or before ridge and lasso (Week 6). ######################################################################## # PART B. MANOVA: several responses at once ######################################################################## # ---- 9) The data: three wines, three chemicals ----------------------- # The wine data from Week 1: 178 wines from three cultivars, each with # 13 chemical measurements. Take three of them, alcohol (%), # flavanoids, and colour intensity, and ask: do the cultivars differ in # their chemistry? # [CORE] wine <- read.csv("https://greymonroe.github.io/PLS_206/data/winedata.csv") table(wine$Cultivar) # [HANDY: the three responses in long format, for plotting] wine_long <- data.frame(Cultivar = rep(wine$Cultivar, 3), response = rep(c("Alcohol", "Flav", "Color"), each = nrow(wine)), value = c(wine$Alcohol, wine$Flav, wine$Color)) wine_long$response <- factor(wine_long$response, levels = c("Alcohol", "Flav", "Color")) # [CORE] p_wine <- ggplot(wine_long, aes(Cultivar, value)) + geom_jitter(width = 0.15, alpha = 0.4) + facet_wrap(~response, scales = "free_y") + labs(x = NULL, y = NULL) + theme_classic(base_size = 14) p_wine # ---- 10) Why not just run three ANOVAs? ------------------------------ # Two reasons. # 1. More tests, more false positives. Three ANOVAs at α = 0.05 give # roughly a 14% chance that at least one is "significant" by luck. # Thirteen chemicals give about 49%. 2. ANOVAs look at one response at # a time, and miss differences that only show up together. This one is # the bigger deal. Here is a demonstration on two wildflower # populations, measuring petal length and petal width (mm). The two # measurements are strongly correlated: long petals are wide petals. # Population B's petals are a little longer and a little narrower for # their length. (Hypothetical, simulated data.) # [DEMO: simulate two populations that differ in petal shape] set.seed(1) petal_pop <- function(n, mean_length, mean_width) { z <- mvrnorm(n, c(mean_length, mean_width), matrix(c(4, 3.6, 3.6, 4), 2)) # correlation 0.9 data.frame(length = z[, 1], width = z[, 2]) } a <- petal_pop(25, 20, 10); a$population <- "A" b <- petal_pop(25, 20.6, 9.4); b$population <- "B" petals <- rbind(a, b) # One ANOVA per response finds nothing: # [DEMO] anova(lm(length ~ population, data = petals)) anova(lm(width ~ population, data = petals)) # Both p-values are about 0.3. Now one MANOVA on both responses # together: # [DEMO] summary(manova(cbind(length, width) ~ population, data = petals)) # p = 2 × 10⁻⁶. The picture shows why: # [DEMO: the two populations, each response alone and both together] pal <- c(A = "#0070C0", B = "#ED7D31") side_l <- ggplot(petals, aes(population, length, colour = population)) + geom_jitter(width = 0.15) + scale_colour_manual(values = pal, guide = "none") + labs(x = NULL, y = "Petal length (mm)", title = "Length alone") + theme_classic(base_size = 14) side_w <- ggplot(petals, aes(population, width, colour = population)) + geom_jitter(width = 0.15) + scale_colour_manual(values = pal, guide = "none") + labs(x = NULL, y = "Petal width (mm)", title = "Width alone") + theme_classic(base_size = 14) both <- ggplot(petals, aes(length, width, colour = population)) + geom_point(size = 2) + scale_colour_manual(values = pal) + labs(x = "Petal length (mm)", y = "Petal width (mm)", title = "Both together") + theme_classic(base_size = 14) (side_l | side_w | both) + plot_layout(widths = c(1, 1, 2)) # Each response on its own is a big overlapping smear. Together, the # two populations sit on two parallel bands: for any petal length, B's # petals are narrower. MANOVA uses the correlation between the # responses, so it sees the shape difference that each single ANOVA # misses. # ---- 11) Fit a MANOVA ------------------------------------------------ # manova() works like lm(), with the responses bound together by # cbind() on the left of the ~. # [CORE] m_wine <- manova(cbind(Alcohol, Flav, Color) ~ Cultivar, data = wine) summary(m_wine, test = "Pillai") # How to read it: # - Pillai's trace (1.47 here) is the test statistic: how much of the # variation in the three responses, taken together, lines up with # cultivar. It runs from 0 (no difference) up to the smaller of the # number of responses and the number of groups minus 1 (2 here). Pillai # is the default and the most robust of the four statistics R offers # ("Wilks", "Hotelling-Lawley", "Roy"); stick with it. - approx F, # Pr(>F): the p-value, < 2 × 10⁻¹⁶. The three cultivars differ in their # chemistry. # ---- 12) Follow up: which responses differ? -------------------------- # A significant MANOVA says the groups differ somewhere. summary.aov() # gives one ANOVA per response, from the same model: # [CORE] summary.aov(m_wine) # All three differ strongly (every p < 2 × 10⁻¹⁶). Plot each response # with its cultivar means and 95% confidence intervals over the raw # data: # [HANDY: cultivar means and 95% CIs for each response] means_ci <- function(response) { m <- lm(reformulate("Cultivar", response), data = wine) nd <- data.frame(Cultivar = sort(unique(wine$Cultivar))) data.frame(nd, response = response, predict(m, nd, interval = "confidence")) } wine_means <- do.call(rbind, lapply(c("Alcohol", "Flav", "Color"), means_ci)) wine_means$response <- factor(wine_means$response, levels = levels(wine_long$response)) # [CORE] p_wine + geom_pointrange(data = wine_means, aes(Cultivar, fit, ymin = lwr, ymax = upr), colour = "red", size = 0.6) # Barolo is highest in alcohol and flavanoids; barbera is lowest in # flavanoids and deepest in colour; grignolino (spelled gringnolino in # the data) is the lightest and lowest in alcohol. For pairwise # comparisons within one response, use TukeyHSD(aov(Flav ~ Cultivar, # data = wine)) as in Week 1. # ---- 13) The discriminant view: which combination separates the groups? --- # MANOVA tests whether the groups differ. Linear discriminant analysis # (LDA) shows how: it finds the weighted combinations of the responses # that pull the groups furthest apart. It is the PCA of between-group # differences. # [CORE] lda_wine <- lda(Cultivar ~ Alcohol + Flav + Color, data = wine) lda_wine$scaling # weights of each response on LD1 and LD2 lda_wine$svd^2 / sum(lda_wine$svd^2) # share of the separation on each axis # [CORE] scores <- data.frame(predict(lda_wine)$x, Cultivar = wine$Cultivar) ggplot(scores, aes(LD1, LD2, colour = Cultivar)) + geom_point(size = 2, alpha = 0.7) + stat_ellipse(linewidth = 1) + theme_classic(base_size = 14) # The three cultivars form three nearly separate clouds. LD1 carries # 72% of the separation, and its largest weight is on flavanoids: LD1 # is mostly the flavanoid axis, splitting low-flavanoid barbera from # the other two. LD2 (28%) is mostly alcohol, splitting high-alcohol # barolo from grignolino. # ---- 14) Assumptions ------------------------------------------------- # MANOVA is the multivariate version of ANOVA, so it inherits ANOVA's # assumptions, each in a multivariate form: # - Independent samples. Same as always. - Residuals roughly normal, # for each response. Check each response's residuals (as in Week 2), # and transform a skewed response first (Part A). - Similar spread # across groups, now for every response and for the correlations # between them (equal covariance matrices). A quick look: the standard # deviation of each response in each group. # [CORE] aggregate(cbind(Alcohol, Flav, Color) ~ Cultivar, data = wine, FUN = sd) # The spreads differ by up to a factor of about 2.5 (colour in barbera # vs grignolino), which Pillai's trace tolerates, especially with # groups of similar size. When the responses are far from normal # (counts with many zeros, presence/absence), or there are more # responses than samples, MANOVA is the wrong tool. That is where # PERMANOVA comes in. ######################################################################## # PART C. PERMANOVA: when the responses are species ######################################################################## # ---- 15) The data: plants in 20 Dutch meadows ------------------------ # The dune data in vegan: cover scores of 30 plant species in 20 # meadows, plus each meadow's management (BF biological farming, HF # hobby farming, NM nature conservation, SF standard farming). Thirty # responses, twenty samples, and mostly zeros: no MANOVA will cope. # [CORE] data(dune, dune.env) dim(dune) mean(dune == 0) # share of zeros table(dune.env$Management) # PERMANOVA works on distances between samples instead of the raw # responses. For species data the usual distance is Bray-Curtis: 0 when # two meadows hold the same species at the same cover, 1 when they # share none. It then asks whether meadows under the same management # are closer to each other than to meadows under other management, and # gets its p-value by shuffling the management labels many times. # ---- 16) Look first: an ordination of the meadows -------------------- # An NMDS (non-metric multidimensional scaling) draws the meadows in # 2-D so that close points have similar species. # [CORE] set.seed(1) nmds <- metaMDS(dune, distance = "bray", k = 2, trace = FALSE) nmds$stress # below 0.2 is a fair 2-D picture # [CORE] pts <- data.frame(scores(nmds, display = "sites"), Management = dune.env$Management) centres <- aggregate(cbind(NMDS1, NMDS2) ~ Management, data = pts, FUN = mean) ggplot(pts, aes(NMDS1, NMDS2, colour = Management)) + geom_point(size = 3) + geom_point(data = centres, shape = 4, size = 6, stroke = 2) + labs(caption = "X = group centroid") + theme_classic(base_size = 14) # The nature-conservation meadows (NM) sit apart from the farmed ones. # PERMANOVA tests whether those centroids differ by more than chance. # ---- 17) Check the assumption first: similar spread ------------------ # PERMANOVA assumes the groups are about equally spread out. If one # group is much more scattered than another, PERMANOVA can call it a # difference in centroids when it is really a difference in spread. # betadisper() measures each meadow's distance to its group centroid, # and permutest() tests whether the groups differ in that. # [CORE] dune_bc <- vegdist(dune, method = "bray") disp <- betadisper(dune_bc, dune.env$Management) set.seed(1) permutest(disp, permutations = 999) # p = 0.15: no evidence that the spreads differ. The assumption holds, # so a PERMANOVA result will be about the centroids. # ---- 18) Run the PERMANOVA ------------------------------------------- # adonis2() takes a formula like lm(), with the whole species table on # the left. # [CORE] set.seed(1) adonis2(dune ~ Management, data = dune.env, method = "bray", permutations = 999) # Management explains 34% of the variation in species composition (R² = # 0.34), p = 0.002: meadows under different management hold different # plant communities. With 999 shuffles the smallest possible p-value is # 0.001, so set set.seed() and report the number of permutations. # Several predictors work like a multiple regression. Use by = "margin" # so each term is tested after the others (the design here is # unbalanced): # [CORE] set.seed(1) adonis2(dune ~ Use + Management, data = dune.env, method = "bray", permutations = 999, by = "margin") # Management still matters (p = 0.006) once land use is accounted for, # while land use adds nothing beyond management (p = 0.38). # ---- 19) Which test, when -------------------------------------------- # | Responses | Test | R | |---|---|---| | One, roughly normal | ANOVA # / linear model | lm(y ~ group) | | Several, roughly normal, more # samples than responses | MANOVA | manova(cbind(y1, y2, y3) ~ group) | # | Many, non-normal, zeros (species, OTUs, gene counts) | PERMANOVA | # adonis2(community ~ group, method = "bray") | # Grey's 2025 slides for this unit are on the [module # page](../modules/manova.qmd) for reference.